<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>角色管理</span>
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            添加角色
          </el-button>
        </div>
      </div>
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="角色名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入角色编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
          >
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" style="margin-top: 10px">
      <el-table
        v-if="roleList.length > 0 || !loading"  
        v-loading="loading"
        :data="roleList || []"
        border
        style="width: 100%"
        empty-text="暂无数据"
        :key="tableKey"
      >
        <el-table-column type="index" width="50" align="center">
          <template #default="{ row }">
            <span v-if="scope?.row">{{ scope.$index + 1 }}</span>  
          </template>
        </el-table-column>
        
        <el-table-column
          prop="name"
          label="角色名称"
          align="center"
          width="150"
        >
          <template #default="{ row }">  <!-- 统一改为新版语法 -->
            <span v-if="row">{{ row.name }}</span>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="code"
          label="角色编码"
          align="center"
          width="150"
        >
          <template #default="{ row }">
            <span v-if="row">{{ row.code }}</span>  <!-- 新增存在性检查 -->
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">  <!-- 新增模板 -->
            <span v-if="row">{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="创建时间"
          align="center"
          width="180"
        >
          <template #default="{ row }">
            <span v-if="row">{{ row.create_time }}</span>  <!-- 新增存在性检查 -->
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="100"
        >
          <template #default="{ row }">  <!-- 改为新版插槽语法 -->
            <el-switch
              v-if="row" 
              v-model="row.status"
              :disabled="row?.code === 'admin'"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button 
              v-if="row && row?.code !== 'admin'"  
              size="small" 
              @click="handlePermission(row)"
            >
              权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改角色对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      @closed="handleDialogClosed"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="请输入角色编码"
            :disabled="form.id !== undefined"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">  
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      title="权限配置"
      v-model="permissionOpen"
      width="600px"
      append-to-body
    >
      <el-form
        ref="permissionForm"
        :model="permissionForm"
        label-width="80px"
      >
        <el-form-item label="角色名称">
          <el-input
            v-model="permissionForm.name"
            disabled
          />
        </el-form-item>
        <el-form-item label="权限" prop="permissionIds">
          <el-tree
            ref="permissionTree"
            :data="permissionOptions"
            :props="{ label: 'name', children: 'children' }"
            show-checkbox
            node-key="id"
            default-expand-all
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPermission">确 定</el-button>
        <el-button @click="permissionCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleList,
  getRoleDetail,
  addRole,
  editRole,
  deleteRole,
  getRolePermissionIds
} from '@/api/role'
import { getPermissionTree } from '@/api/permission'
import Pagination from '@/components/Pagination'

export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],  // 初始化为空数组
      // 弹出层标题
      title: '添加角色',
      // 是否显示弹出层
      open: false,
      // 是否显示权限配置弹出层
      permissionOpen: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        name: undefined,
        code: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        permissionIds: []  // 确保数组类型初始化
      },
      // 权限表单参数
      permissionForm: {
        id: undefined,
        name: undefined,
        permissionIds: []
      },
      // 状态数据字典
      statusOptions: [
        {
          value: 1,
          label: '正常'
        },
        {
          value: 0,
          label: '停用'
        }
      ],
      // 权限树选项
      permissionOptions: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '角色编码不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      getRoleList(this.queryParams).then(response => {
        this.roleList = (response.data.data || []).filter(item => !!item)
        this.total = response.data.total || 0
        this.loading = false
        this.tableKey += 1  // 强制表格重新渲染
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        pageSize: 10,
        name: undefined,
        code: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    /** 状态修改 */
    handleStatusChange(row) {
      if (!row) return  // 新增空值检查
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm(`确认要${text}角色"${row.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return editRole({ id: row.id, status: row.status })
      }).then(() => {
        this.$message.success(`${text}成功`)
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加角色'
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.reset()
      getRoleDetail(row.id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '编辑角色'
      })
    },
    /** 权限配置操作 */
    handlePermission(row) {
      this.permissionForm = {
        id: row.id,
        name: row.name,
        code:row.code,
        description:row.description,
        status:row.status,
        permissionIds: []
      }
      // 获取权限树
      getPermissionTree().then(response => {
        this.permissionOptions = response.data || []  
        // 获取角色拥有的权限
        getRolePermissionIds(row.id).then(res => {
          this.$nextTick(() => {
            this.$refs.permissionTree.setCheckedKeys(res.data || [])  
          })
          this.permissionOpen = true
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`确认删除角色"${row.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteRole(row.id)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        code: undefined,
        description: undefined,
        status: 1,
        permissionIds: []
      }
      this.resetForm('form')
    },
    /** 重置表单 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
    },
    /** 权限取消按钮 */
    permissionCancel() {
      this.permissionOpen = false
    },
    /** 对话框关闭时的回调 */
    handleDialogClosed() {
      this.reset()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            editRole(this.form).then(response => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRole(this.form).then(response => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 提交权限 */
    submitPermission() {
      const permissionIds = this.$refs.permissionTree.getCheckedKeys()
      const halfPermissionIds = this.$refs.permissionTree.getHalfCheckedKeys()
      // 合并选中和半选的权限ID
      const allPermissionIds = permissionIds.concat(halfPermissionIds)
      
      editRole({
        id: this.permissionForm.id,
        name:this.permissionForm.name,
        code:this.permissionForm.code,
        description:this.permissionForm.description,
        status:this.permissionForm.status,
        permissionIds: allPermissionIds
      }).then(response => {
        this.$message.success('权限配置成功')
        this.permissionOpen = false
      })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 10px;
}
</style>
